# Definition for a Node.
class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None
        self.parent = None


class Solution:
    def flipBinaryTree(self, root: 'Node', leaf: 'Node') -> 'Node':
        if root == leaf:
            return root

        leaf.left = leaf.parent
        leaf.parent = None

        node = leaf
        while node.left != root:
            if node.left.right == node:
                node.left.right = node.left.left

            node.left.left = node.left.parent
            node.left.parent = node

            node = node.left

        if node.left.left == node:
            node.left.left = None
        else:
            node.left.right = None

        node.left.parent = node

        return leaf


if __name__ == "__main__":
    pass
